<template>
    <!-- 使用 Element Plus 的表格组件展示数据 -->
    <div class="main-container">
        <el-table :data="getroleList" style="width: 100%;height: 100%" border stripe>
            <!-- 固定列，显示角色编号 -->
            <el-table-column fixed prop="roleId" label="角色编号" width="100" />
            <!-- 显示角色名称 -->
            <el-table-column prop="roleName" label="角色名称" width="100">
                <template #default="scope">
                    <el-button 
                        @click="ejectVisible = true; Getuserrole(scope.row.roleId); openAssignDialog(scope.row.roleName);">{{
                            scope.row.roleName
                        }}</el-button>
                </template>
            </el-table-column>
            <!-- 显示创建人名称 -->
            <el-table-column prop="userName" label="创建人名称" width="100" />
            <!-- 显示创建时间，只显示日期部分 -->
            <el-table-column prop="createTime" label="创建时间" width="100">
                <template #default="scope">
                    {{ scope.row.createTime.split('T')[0] }}
                </template>
            </el-table-column>
            <!-- 显示修改人编号 -->
            <el-table-column prop="updateid" label="修改人编号" width="100" />
            <!-- 显示修改时间，只显示日期部分 -->
            <el-table-column prop="updateTime" label="修改时间" width="100">
                <template #default="scope">
                    {{ scope.row.updateTime.split('T')[0] }}
                </template>
            </el-table-column>
            <!-- 固定在右侧的操作列 -->
            <el-table-column fixed="right" label="操作" min-width="100">
                <template #default="scope">
                    <!-- 删除角色按钮 -->
                    <el-button type="danger" @click="DelRole(scope.row.roleId)">删除</el-button>
                    <!-- 分配人员按钮 -->
                    <el-button type="warning"
                        @click="openAssignDialog(scope.row.roleName); fenp(scope.row.roleId); dialogFormVisible = true;">分配人员</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分配人员弹窗 -->
        <el-dialog v-model="dialogFormVisible" title="分配人员" width="500" style="height: 270px;" class="custom-dialog">
            请设置【{{ roleName }}】角色的员工:
            <div class="tree-container">
                <div class="left-tree">
                    <!-- 添加 node-click 事件 -->
                    <el-tree style="max-width: 150px" :data="data2" show-checkbox node-key="id" :props="defaultProps"
                        ref="leftTreeRef" @check-change="handleNodeClick">
                    </el-tree>
                </div>
                <div class="right-tree">
                    <el-tree style="max-width: 150px" :data="rolequeryList" show-checkbox node-key="roleId"
                        :props="roleProps" ref="rightTreeRef">
                    </el-tree>
                </div>
            </div>
            <div class="button-container">
                <el-button type="primary" @click="fen()">分配</el-button>
            </div>
        </el-dialog>
        <el-dialog v-model="ejectVisible" width="500" style="height: 270px;" class="custom-dialog">
            属于角色【{{ roleName }}】的员工如下:
            <el-table :data="getuserroleList" style="width: 100%;height: 100%" border stripe>
                <!-- 显示角色名称 -->
                <el-table-column prop="userName" label="角色名称" width="150" />
                <el-table-column fixed="right" label="操作" min-width="100">
                    <template #default="scope">
                        <!-- 删除角色按钮 -->
                        <!-- <el-button type="danger" >删除</el-button> -->
                        <!-- 分配人员按钮 -->
                        <el-button type="warning" @click="openAssignDialog(scope.row.roleName); fenp(scope.row.roleId); dialogFormVisible = true;">分配人员</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
import { useRouter } from 'vue-router'
import { ElTree, ElTreeSelect } from 'element-plus'
import { read, write } from "@/axios/axiosHelper"

const dialogFormVisible = ref(false);
// 定义 roleName 变量
const roleName = ref('');
// 定义 ejectVisible 变量
const ejectVisible = ref(false);

// 部门数据
const data2 = [
    {
        id: 0,
        label: '请选择部门',
        children: [
            {
                id: 1,
                label: 'IT信息部',
            },
            {
                id: 2,
                label: '人力资源部',
            },
            {
                id: 3,
                label: '财务部',
            },
            {
                id: 4,
                label: '销售部',
            },
            {
                id: 5,
                label: '行政部',
            },
        ],
    },
];

// 表格数据
const getroleList = ref([]);

// 组件挂载后获取角色数据
onMounted(() => {
    GetRole1()
})

// 分页信息
const getrolepage = ref({
    pageIndex: 1,
    pageSize: 15
})

// 获取角色数据的方法
const GetRole1 = () => {
    read.get('/read/api/Role/GetRole2', {
        params: {
            pageIndex: getrolepage.value.pageIndex,
            pageSize: getrolepage.value.pageSize
        }
    }).then((res) => {
        console.log(res)
        getroleList.value = res.data.data
    })
}

const getuserroleList = ref([]);
const Getuserrole = (roleId: number) => {
    read.get('/read/api/UserRole/GetUserRole2', {
        params: {
            roleId: roleId
        }
    }).then((res) => {
        console.log(res)
        getuserroleList.value = res.data.data
    })
}

// 删除操作
const DelRole = (roleId: number) => {
    ElMessageBox.confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        write.put('/write/api/Role/DelRole', {
            RoleId: roleId
        }).then((res) => {
            console.log(res)
            if (res.data.code === 400) {
                ElMessage({
                    type: 'success',
                    message: '删除成功!'
                })
                GetRole1();
            }
        })
    })
}

const fenplist = ref(0);
const fenp = (roleId: number) => {
    fenplist.value = roleId;
}

// 打开分配人员对话框并赋值 roleName
const openAssignDialog = (name: string) => {
    roleName.value = name;
}

// 定义左右树的引用
const leftTreeRef = ref<InstanceType<typeof ElTree>>()
const rightTreeRef = ref<InstanceType<typeof ElTree>>()

// 定义角色数据的 props
const roleProps = {
    label: 'roleName',
    children: 'children' // 如果有子节点的话
}

// 定义部门数据的 props
const defaultProps = {
    label: 'label',
    children: 'children'
}

// 定义 RoleQuery 对象
const RoleQuery = reactive({
    DepartmentId: ''
})

// 右侧树形结构的数据
const rolequeryList = ref([]);

// 处理节点点击事件
const handleNodeClick = () => {
    // 获取所有选中节点的 id
    const selectedIds = leftTreeRef.value?.getCheckedKeys() || [];
    // 将 id 数组转换为逗号分隔的字符串
    const idString = selectedIds.join(',');
    console.log('Selected Department IDs:', idString);
    RoleQuery.DepartmentId = idString;

    // 假设根据 DepartmentId 获取右侧树形结构的数据
    read.get('/read/api/Role/GetRole', {
        params: {
            pageIndex: getrolepage.value.pageIndex,
            pageSize: getrolepage.value.pageSize,
            departmentId: RoleQuery.DepartmentId
        }
    }).then((res) => {
        rolequeryList.value = res.data.data;
    }).catch((error) => {
        console.error('获取右侧树形结构数据失败:', error);
        ElMessage({
            type: 'error',
            message: '获取右侧树形结构数据失败，请稍后重试'
        });
    });
}

// 分配按钮点击事件
const fen = () => {
    const rightSelectedIds = rightTreeRef.value?.getCheckedKeys() || [];

    write.post('/write/api/Main/Handle', {
        userRoles: fenplist.value,
        roleId: rightSelectedIds,
    }).then((res) => {
        ElMessage.success('分配成功!');
        dialogFormVisible.value = false;
    }).catch((error) => {
        console.error('分配失败:', error);
        ElMessage.error('分配失败，请稍后重试');
    });
}
</script>

<style scoped>
.main-container {
    padding: 20px;
    background-color: #f4f4f4;
    border-radius: 8px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

.el-table {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;
}

.left-tree,
.right-tree {
    min-width: 150px; /* 最小宽度 */
    flex: 1; /* 自适应剩余空间 */
}

.el-table:hover {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.custom-dialog {
    max-height: 80vh; /* 最大高度为视口的 80% */
    overflow-y: auto; /* 内容过多时显示滚动条 */
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

.tree-container {
    display: flex;
    align-items: flex-start;
    padding: 10px;
}

.left-tree,
.right-tree {
    margin-right: 50px;
    width: 150px;
}

.button-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
    padding: 0 10px;
}

.el-button {
    border-radius: 4px;
    transition: background-color 0.3s ease;
}

.el-button--danger {
    background-color: #f56c6c;
}

.el-button--danger:hover {
    background-color: #f78989;
}

.el-button--warning {
    background-color: #e6a23c;
}

.el-button--warning:hover {
    background-color: #ebb563;
}

.el-button--primary {
    background-color: #409eff;
}

.el-button--primary:hover {
    background-color: #66b1ff;
}
</style>